const router = require('koa-router')()
const Person = require('../dbs/models/person')

router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})

// 增加person
router.post('/addPerson', async function (ctx, next) {
  const person = new Person({
    name:ctx.request.body.name,
    age:ctx.request.body.age,
  })

  let code
  try {
    await person.save()
    code = 0
  }catch (e) {
    code = 10002
  }

  ctx.body = {
    code: code
  }
})

router.post('/findPerson', async function (ctx, next) {
  let name = ctx.request.body.name;

  let result = await Person.findOne({name:name})
  let results = await Person.find({name:name})

  ctx.body = {
    code: 0,
    result,
    results
  }
})

router.post('/updatePerson', async function (ctx, next) {
  let {name,age} = ctx.request.body;

  await Person.where({name:name}).update({age:age})

  ctx.body = {
    code: 0
  }
})


router.post('/removePerson', async function (ctx, next) {
  let {name} = ctx.request.body;

  await Person.where({name:name}).remove()

  ctx.body = {
    code: 0
  }
})

module.exports = router
